package com.anbow.courseware.controller;

import com.anbow.courseware.entity.DTO.TeachingQuestionsDTO;
import com.anbow.courseware.entity.DTO.VipTeachingQuestionsDTO;
import com.anbow.courseware.entity.FORM.VipTeachingQuestionsForm;
import com.anbow.courseware.entity.VO.VipTeachingQuestionsVO;
import com.anbow.courseware.service.impl.TeachingQuestionsServiceImpl;
import com.anbow.courseware.service.impl.VipTeachingQuestionsServiceImpl;
import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author zhaoYuFei
 */
@Controller
@RequestMapping("/vipTeachingQuestions")
public class VipTeachingQuestionsController {
    @Autowired
    private VipTeachingQuestionsServiceImpl vipTeachingQuestionsService;
    @Autowired
    private TeachingQuestionsServiceImpl teachingQuestionsService;

    @GetMapping("/clear")
    public String clear(HttpSession session) {
        session.setAttribute("label", null);
        List<TeachingQuestionsDTO> collect = teachingQuestionsService.getAll();
        List<VipTeachingQuestionsDTO> collect1 = vipTeachingQuestionsService.getAll();
        session.setAttribute("total", collect.size());
        session.setAttribute("totalVip", collect1.size());
        session.setAttribute("list", collect.subList(0, collect.size() > 10 ? 10 : collect.size()));
        session.setAttribute("vipList", collect1.subList(0, Math.min(collect1.size(), 10)));
        return "vip";
    }


    @GetMapping("/getByLabel")
    public String getByLabel(@RequestParam(value = "label", required = false) String label,
                             @RequestParam(value = "pageNum", required = false) Integer pageNum, HttpSession session) {
        List<VipTeachingQuestionsDTO> list = vipTeachingQuestionsService.getLabel(label, pageNum);
        List<VipTeachingQuestionsVO> collect = list.stream().map(e -> {
            VipTeachingQuestionsVO vipTeachingQuestionsVO = new VipTeachingQuestionsVO();
            BeanUtils.copyProperties(e, vipTeachingQuestionsVO);
            return vipTeachingQuestionsVO;
        }).collect(Collectors.toList());
        session.setAttribute("vipList", collect);
        session.setAttribute("label", label);
        session.setAttribute("totalVip", collect.size());

        return "vip";
    }


    @GetMapping("/getByLabelToPage")
    public String getByLabelToPage(@RequestParam(value = "label", required = false) String label,
                             @RequestParam(value = "pageNum", required = false) Integer pageNum, HttpSession session) {
        List<VipTeachingQuestionsDTO> list = vipTeachingQuestionsService.getLabel(label, pageNum);
        List<VipTeachingQuestionsVO> collect = list.stream().map(e -> {
            VipTeachingQuestionsVO vipTeachingQuestionsVO = new VipTeachingQuestionsVO();
            BeanUtils.copyProperties(e, vipTeachingQuestionsVO);
            return vipTeachingQuestionsVO;
        }).collect(Collectors.toList());
        session.setAttribute("vipList", collect);
        session.setAttribute("label", label);
        return "vip";
    }

    @GetMapping("/getById/{id}")
    private String getById(@PathVariable("id") String id, HttpSession session) {
        VipTeachingQuestionsDTO vipTeachingQuestionsDTO = vipTeachingQuestionsService.getById(id);
        session.setAttribute("updateData", vipTeachingQuestionsDTO);
        session.setAttribute("context", vipTeachingQuestionsDTO.getContext());
        session.setAttribute("id", vipTeachingQuestionsDTO.getId());
        session.setAttribute("title", vipTeachingQuestionsDTO.getTitle());
        session.setAttribute("label", vipTeachingQuestionsDTO.getLabel());
        session.setAttribute("result", vipTeachingQuestionsDTO.getResult());
        return "vip";
    }

    @PostMapping("/delete/{id}")
    private String delete(@PathVariable("id") String id) {
        vipTeachingQuestionsService.deleteById(id);
        return "vip";
    }

    @PostMapping("/update")
    private String update(@RequestParam("title") String title, @RequestParam("label") String label,
                          @RequestParam("context") String context) {
        VipTeachingQuestionsForm vipTeachingQuestionsForm = new VipTeachingQuestionsForm();
        vipTeachingQuestionsForm.setTitle(title);
        vipTeachingQuestionsForm.setLabel(label);
        vipTeachingQuestionsForm.setContext(context);
        vipTeachingQuestionsForm.setUpdateTime(LocalDate.now());
        vipTeachingQuestionsService.update(vipTeachingQuestionsForm);
        return "vip";
    }


    @PostMapping("/outs/{ids}")
    public void out(@PathVariable String ids, HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        StringBuilder context = vipTeachingQuestionsService.getByIds(ids);
        StringBuffer sbf = new StringBuffer();
        sbf.append("<html><body>");
        sbf.append(context);
        sbf.append("</body></html>");
        exportWord(request, response, String.valueOf(sbf), "word");
    }

    /**
     * @param request
     * @param response
     * @param content  富文本内容
     * @param fileName 生成word名字
     * @throws Exception
     */
    public static void exportWord(HttpServletRequest request, HttpServletResponse response, String content,
                                  String fileName) throws Exception {
        byte b[] = content.getBytes("GBK"); //这里是必须要设置编码的，不然导出中文就会乱码。
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais); //该步骤不可省略，否则会出现乱码。
        //输出文件
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/msword");//导出word格式
        response.addHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("GB2312"), "iso8859-1") + ".doc");
        ServletOutputStream ostream = response.getOutputStream();
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
        poifs.close();
    }

}
